﻿using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.Utilities;
using System.IO;
using Microsoft.SharePoint;

namespace zevenseas.SharePoint.Solutions.FeatureBlocker.ApplicationPages
{
    public class FeatureBlockerTimerJob : SPJobDefinition
    {
        //Assembly file
        private const string binPath = "bin";
        private const string assemblyName = "zevenseas.SharePoint.Solutions.FeatureBlocker.dll";

        //Browser file
        private const string appBrowserPath = "App_Browsers";
        private const string browserFile = "zevenseasFeatureBlocker.browser";
        private const string featureName = "zsFeatureBlocker";

        [Persisted]
        protected bool processed;

        [Persisted]
        public bool Installing;

        public bool Processed { get; set; }

        public FeatureBlockerTimerJob()
            : base()
        {

        }

        public FeatureBlockerTimerJob(string name, SPWebApplication webApplication, SPServer server, SPJobLockType lockType)
            : base(name, webApplication, server, lockType)
        {
        }

        public override void Execute(Guid targetInstanceId)
        {
            //if (!this.processed)
            //{
                foreach (KeyValuePair<SPUrlZone, SPIisSettings> zoneSettings in this.WebApplication.IisSettings)
                {
                    string applicationRoot = zoneSettings.Value.Path.FullName;
                    string appBrowserFolder = Path.Combine(applicationRoot, appBrowserPath);
                    string targetFile = Path.Combine(appBrowserFolder, browserFile);
                    string cacheToggleFile = Path.Combine(appBrowserFolder, "compat.browser");
                    string filePath = String.Format("{0}\\FEATURES\\{1}\\{2}", SPUtility.GetGenericSetupPath("Template"), featureName, browserFile);

                    if (this.Installing)
                    {
                        File.Copy(filePath, targetFile, true);
                    }
                    else if (File.Exists(targetFile))
                    {
                        File.Delete(targetFile);
                    }

                    //Toggle the .browser file to force an AppPool Recycle
                    File.SetLastWriteTime(cacheToggleFile, DateTime.Now);
                }

            //    this.processed = true;
            //    this.Update();
            //}

            base.Execute(targetInstanceId);
        }
    }
}
